package cn.e2win.biz.m;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e2win.base.controller.MyException;
import cn.e2win.base.entity.SysCompany;
import cn.e2win.base.entity.SysUser;
import cn.e2win.base.json.vo.Pager;
import cn.e2win.base.json.vo.Result;
import cn.e2win.base.json.vo.WeixinUser;
import cn.e2win.biz.activity.ActivityService;
import cn.e2win.biz.annotation.PageParam;
import cn.e2win.biz.base.BaseController;
import cn.e2win.biz.base.BaseService;
import cn.e2win.biz.comm.WeiXinController;
import cn.e2win.biz.dbo.BaseEmp;
import cn.e2win.biz.dbo.CygsEmp;
import cn.e2win.biz.dbo.CyzjEmp;
import cn.e2win.biz.dbo.CyzjOrg;
import cn.e2win.biz.dbo.DsEmp;
import cn.e2win.biz.dbo.ZdzxEmp;
import cn.e2win.biz.notice.NoticeService;
import cn.e2win.biz.user.UserDao;
import cn.e2win.biz.user.UserService;
import cn.e2win.biz.util.StringUtils;  

/**
 * Created by lenovo on 2016/11/7.
 */
@Controller
@Scope("request")
@RequestMapping("m")
public class IndexController extends BaseController {

    @Autowired
    private UserDao userDao;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Override
    public BaseService initService() {

        return userService;
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request ,ModelMap modelMap) {
        if(pager.getCurrUser()!=null) {
            pager.getScMap().put("toUserId", pager.getCurrUser().getId() + "");
            pager.getScMap().put("readStatus", "unRead");
            noticeService.pagerNotice(pager);
            modelMap.addAttribute("noReadMessage", pager.getTotalCount());
        }else{
            modelMap.addAttribute("noReadMessage", 0);
        }
        Pager temp = new Pager();
        temp.getScMap().put("beginTime_B", StringUtils.getNowTimes("yyyy-MM-dd"));
        temp.getScMap().put("approveStatus", "APPROVED");
        temp.getScMap().put("activeStatusInt", "1");
        activityService.pagerActivity(temp);
        modelMap.put("topActivity", temp.getResultList());
        //TODO modelMap.putAll(WeiXinController.getWxConfig(request));
        return "/m/main";
    }
    
  
    
    
    

    @RequestMapping("/main")
    public String main(HttpServletRequest request ,ModelMap modelMap,HttpSession session){
    	//TODO 此处有两个动作要处理，
    	//未登录时在此处获取weixin USER
    	//已登录时直接跳转
	
			SysUser user = null;
			//判断是否是超级管理员--配置文件中配置的
			String errMsg = null;
			try{
	
				WeixinUser weixinUser = (WeixinUser) request.getSession().getAttribute("weixinUser");
				String username = request.getParameter("account");
				String password = request.getParameter("password");
				List<SysUser> list = null;
				
			if(weixinUser == null || StringUtils.isEmpty(weixinUser.getOpenid())){
				//System.err.println("1111111======== 普通登录！");
				//验证用户账号与密码是否对应
				username = username.trim();
				list= userDao.getUserByAccount(username);
				
				if(list==null || list.size()!=1){
					errMsg = "登录失败，帐号或密码错误!";
					throw new AuthenticationServiceException(errMsg);
				}else{
					user = list.get(0);
					if(!user.getPassword().equals(password)) {
						errMsg = "登录失败，帐号或密码错误!";
						throw new AuthenticationServiceException(errMsg);
					}
				}
			}else{
				//System.err.println("222222======== 微信登录！");
				list = userDao.getUserByOpenId(weixinUser.getOpenid());
                //System.err.println("user集合size。。。"+list.size());
                if(list==null || list.size()!=1){
					System.err.println("222222========根据openId"+weixinUser.getOpenid()+"找不到用户");
					if(StringUtils.isEmpty(username)){
						errMsg = "欢迎登录！";
						throw new AuthenticationServiceException(errMsg);
					}else{
						//System.err.println("222222======== 按帐号登录！");
						list= userDao.getUserByAccount(username);
						if(list==null || list.size()!=1){
							//System.err.println("222222======== 找不到帐号！");
							errMsg = "登录失败，帐号或密码错误!";
							throw new AuthenticationServiceException(errMsg);
						}else{
							user = list.get(0);
							if(!user.getPassword().equals(password)) {
								errMsg = "登录失败，帐号或密码错误!";
								throw new AuthenticationServiceException(errMsg);
							}
							user.setOpenId(weixinUser.getOpenid());
							userService.processOpenId4LoginAndOut(weixinUser.getOpenid(),user, "LOGIN");
							//System.err.println(weixinUser.getOpenid()+"更新openId.....");
							//System.err.println("222222======== 找到帐号！");
						}
					}
				}else{
					System.err.println("222222======== 找到openId 并找到用户！");
					user = list.get(0);
					//System.err.println("222222======== 更新数据库完成！");
				}
				
			}
			
			
		

			//System.err.println("333333===========！");
			if(user.getActiveStatusInt()!=1) {
				errMsg = "该帐号已被停用！";
				throw new AuthenticationServiceException(errMsg); 
			}
			//System.err.println("444444===========！");
			SysCompany company = (SysCompany)this.userDao.getEntity(SysCompany.class, user.getCoId());
			if(company.getActiveStatusInt()!=1){
				errMsg = "公司帐号已被停用！";
				throw new AuthenticationServiceException(errMsg); 
			}
			if(company.getExpireDate()==null || company.getExpireDate().before(new Date())){
				errMsg = "公司服务合同已到期，续费后方可启用！";
				throw new AuthenticationServiceException(errMsg); 
			}

			//System.err.println("55555===========！");
			/**
			 * 验证emp状态
			 */
			String userType = user.getUserType();
			BaseEmp sysEmp = null;
			if(userType.equals("DsEmp")){
				sysEmp = (BaseEmp) userDao.getEntity(DsEmp.class,user.getEmpId());
			}else if(userType.equals("CyzjEmp")){
				sysEmp = (BaseEmp) userDao.getEntity(CyzjEmp.class,user.getEmpId());
				CyzjOrg cyzjOrg = (CyzjOrg) userDao.getEntity(CyzjOrg.class,sysEmp.getOrgId());
				if(!cyzjOrg.getActiveStatusInt().equals(1) || !cyzjOrg.getApproveStatus().equals("APPROVED")){
					errMsg = "创业之家未通过审核！";
					throw new AuthenticationServiceException(errMsg);
				}
			}else if(userType.equals("ZdzxEmp")){
				sysEmp = (BaseEmp) userDao.getEntity(ZdzxEmp.class,user.getEmpId());
			}
			if(sysEmp.getActiveStatusInt().equals("0") || !sysEmp.getApproveStatus().equals("APPROVED")){
				errMsg = "该账号已被停用或未通过审核！";
				throw new AuthenticationServiceException(errMsg);
			}

			//System.err.println("66666666===========！");
	        BaseEmp currEmp = null;
	        if("CyzjEmp".equals(user.getUserType())){
	        	currEmp = (CyzjEmp) userDao.getEntity(CyzjEmp.class,user.getEmpId());
	        }else if("CygsEmp".equals(user.getUserType())){
	        	currEmp = (CygsEmp) userDao.getEntity(CygsEmp.class,user.getEmpId());
	        }else if("DsEmp".equals(user.getUserType())){
	        	currEmp = (DsEmp) userDao.getEntity(DsEmp.class,user.getEmpId());
	        }else if("ZdzxEmp".equals(user.getUserType())){
	            currEmp = (ZdzxEmp) userDao.getEntity(ZdzxEmp.class,user.getEmpId());
	        }
			//System.err.println("7777777===========！");
			request.getSession().setAttribute("currEmp", currEmp);
		}catch(Exception e){
			request.setAttribute("errMsg", errMsg);
	        return "/m/login";
		}
		//System.err.println("登录成功!====================login successful");

		request.getSession().setAttribute("user", user);
        //return "/m/main";

        return "redirect:/m/index.do";
    }
    
    
//    @RequestMapping("/create")
//    public String create(HttpServletRequest request, @PageParam Pager pager,
//                        ModelMap modelMap) {
//        return "/m/create";
//    }

    @RequestMapping("/search")
    public String search(HttpServletRequest request,String type,
                              ModelMap modelMap) {
        modelMap.addAttribute("type",type);
        return "/m/search";
    }

    @RequestMapping("/toSearch")
    @ResponseBody
    public Result toSearch(HttpServletRequest request,
                           @RequestParam(value = "type",required = false) String type,
                           @RequestParam(value = "title",required = false) String title,
                           ModelMap modelMap) {
        Result result = new Result();
        if(type.equals("ds")) {
            result.setForwardUrl("dsMain.do?map.title_I="+title);
        }else if(type.equals("cyzj")){
            result.setForwardUrl("cyzjMain.do?map.title_I="+title);
        }else if(type.equals("activity")){
            result.setForwardUrl("activityMain.do?map.title_I="+title);
        }
        return result;
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, @PageParam Pager pager,
                         ModelMap modelMap) {
        return "/m/login";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, @PageParam Pager pager,
                         ModelMap modelMap) throws MyException {

		WeixinUser weixinUser = (WeixinUser) request.getSession().getAttribute("weixinUser");
		SysUser user = (SysUser) request.getSession().getAttribute("user");
    	if(weixinUser!=null){
    		userService.processOpenId4LoginAndOut(weixinUser.getOpenid(),user, "LOGOUT");
    	}
    	request.getSession().removeAttribute("weixinUser");
     	request.getSession().removeAttribute("currEmp");
    	request.getSession().removeAttribute("user");
        return "/m/login";
    }

    @RequestMapping("/myQuestion")
    public String myQuestion(HttpServletRequest request, @PageParam Pager pager,
                        ModelMap modelMap) {
        return "/m/myQuestion";
    }

    @RequestMapping("/myAnswer")
    public String myAnswer(HttpServletRequest request, @PageParam Pager pager,
                             ModelMap modelMap) {
        return "/m/myAnswer";
    }

    @RequestMapping("/myHelp")
    public String myHelp(HttpServletRequest request, @PageParam Pager pager,
                           ModelMap modelMap) {
        return "/m/myHelp";
    }

    @RequestMapping("/myFavorite")
    public String myFavorite(HttpServletRequest request, @PageParam Pager pager,
                         ModelMap modelMap) {
        return "/m/myFavorite";
    }

    @RequestMapping("/myInfo")
    public String myInfo(HttpSession httpSession,
                         ModelMap modelMap) {
        SysUser sysUser = (SysUser) httpSession.getAttribute("user");
        if(sysUser==null || sysUser.getUserType()==null || sysUser.getEmpId()==null){
            return "redirect:/m/login.do";
        }
        BaseEmp currEmp = null;
        if("CyzjEmp".equals(sysUser.getUserType())){
        	currEmp = (CyzjEmp) userDao.getEntity(CyzjEmp.class,sysUser.getEmpId());
        }else if("CygsEmp".equals(sysUser.getUserType())){
        	currEmp = (CygsEmp) userDao.getEntity(CygsEmp.class,sysUser.getEmpId());
        }else if("DsEmp".equals(sysUser.getUserType())){
        	currEmp = (DsEmp) userDao.getEntity(DsEmp.class,sysUser.getEmpId());
        }else if("ZdzxEmp".equals(sysUser.getUserType())){
            currEmp = (ZdzxEmp) userDao.getEntity(ZdzxEmp.class,sysUser.getEmpId());
        }
        else{
        	return "redirect:/m/login.do";
        }
        
        if(currEmp==null){
            return "redirect:/m/index.do";
        }else{
            httpSession.setAttribute("currEmp",currEmp);
        }
        return "/m/myInfo";
    }

    @RequestMapping("/myPersonal")
    public String myPersonal(HttpServletRequest request, @PageParam Pager pager,
                             ModelMap modelMap) {
    	String returnJsp = "/m/dsSelfInfo";
		SysUser user = (SysUser) request.getSession().getAttribute("user");

        if("DsEmp".equals(user.getUserType())){
        	returnJsp = "/m/selfInfoDsEmp";
        }else if("CyzjEmp".equals(user.getUserType())){
        	returnJsp = "/m/selfInfoCyzjEmp";
        }else if("ZdzxEmp".equals(user.getUserType())){
        	returnJsp = "/m/selfInfoZdzxEmp";
        }
    	
        return returnJsp;
    }

    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request,@ModelAttribute SysUser sysUser,HttpSession session,
                          ModelMap modelMap) {
//        Result result = new Result();
        try {
        	SysUser user = null;
        	List<SysUser> list= userDao.getUserByAccount(sysUser.getAccount());
    		if(list==null || list.size()==0){
                throw new MyException("账号不存在");
    		}else if(list.size()!=1){
                throw new MyException("账号重复，请与系统管理员联系");
    		}else{
    			user = list.get(0);
    		}
            if(user.getPassword().equals(sysUser.getPassword())){
                session.setAttribute("user",user);
            }else{
                throw new MyException("密码错误");
            }
        } catch (MyException e) {
            return "redirect:/m/login.do";
//            result.setStatusCode(Result.FAILED);
//            result.setMessage(e.getMessage());
        }catch (Exception e) {
//            result.setStatusCode(Result.FAILED);
//            result.setMessage(e.getMessage());
            return "redirect:/m/login.do";
        }
        myInfo(session,modelMap);
        return "redirect:/m/index.do";
    }

}
